package com.textjelly.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.textjelly.client.GreetingService;
import com.textjelly.shared.FieldVerifier;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String number, String message) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(number)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script vulnerabilities.
		number = escapeHtml(number);

		CarrierType carrier = null;
		String to = "";
		try {
			carrier = fetchCarrierType(number);
			to = number+"@"+carrier.getExtension();
			sendMessage(to, message);
		} catch (Exception e) {
			// TODO Handle exception
			e.printStackTrace();
		}
		
		return to;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	
	public enum CarrierType {
		VERIZON("vtext.com"), ATT("txt.att.net"), TMOBILE("tmomail.net"), SPRINT("messaging.sprintpcs.com"),
		  BOOST("myboostmobile.com"), VIRGIN("vmobl.com");
		
		private String extension;
		
		CarrierType(String s) {
			extension = s;
		}
		
		String getExtension() {
			return extension;
		}
	}

	private CarrierType fetchCarrierType(String phoneNumber) throws Exception {

		String areaCode = null;
		String prefix = null;
		String lineNumber = null;
		if (phoneNumber == null || phoneNumber.trim().length() < 10) {
			return null;
		}

		areaCode = phoneNumber.substring(0, 3);
		prefix = phoneNumber.substring(3, 6);
		lineNumber = phoneNumber.substring(6);

		String baseUrl = null;
		baseUrl = "http://www.fonefinder.net/findome.php?npa=" + areaCode
				+ "&nxx=" + prefix + "&thoublock=" + lineNumber
				+ "&usaquerytype=Search+by+Number";
		URL url = new URL(baseUrl);
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);

		BufferedReader in = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));

		String decodedString;
		StringBuilder builder = new StringBuilder();
		while ((decodedString = in.readLine()) != null) {
			System.out.println(decodedString);
			builder.append(decodedString);
		}

		in.close();
		return findCarrier(builder.toString());
	}

	private CarrierType findCarrier(String responseMarkup) {

		String lowerCaseResponse = responseMarkup.toLowerCase();
		
		if (lowerCaseResponse.contains("verizon.php"))
			{return CarrierType.VERIZON;}
		else if (lowerCaseResponse.contains("att.php"))
			{return CarrierType.ATT;}
		else if (lowerCaseResponse.contains("sprint.php"))
			{return CarrierType.SPRINT;}
		else
		{
			throw new RuntimeException("Error finding carrier.");
		}
	}
	
	private void sendMessage(String to, String message) {
		
		Properties properties = new Properties();
		Session session = Session.getDefaultInstance(properties, null);
		
		try {
			Message msg = new MimeMessage(session);
	        msg.setFrom(new InternetAddress("david.der@gmail.com", "Text Jelly"));
	        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
	        msg.setSubject("Message from Text Jelly");
	        msg.setText(message);
	        Transport.send(msg); 
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
